package com.yuan.blog.controller.web;

import com.yuan.blog.core.utils.R;
import com.yuan.blog.entity.InvitataionEntity;
import com.yuan.blog.entity.UserEntity;
import com.yuan.blog.exception.JsonException;
import com.yuan.blog.service.ICommentService;
import com.yuan.blog.service.IInvitataionService;
import com.yuan.blog.service.IUserService;
import com.yuan.blog.vo.CommentVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @program: com.yuan.blog
 * @description:
 * @author: yuan_boss
 * @create: 2022-12-05 21:03
 **/
@Controller
@RequestMapping("/InvitationController")
public class InvitationController{

    @Autowired
    private IInvitataionService invitationService;
    @Autowired
    private ICommentService commentService;
    @Autowired
    private IUserService userService;

    @PostMapping("/publish")
    @ResponseBody
    public R publish(@RequestBody InvitataionEntity invitataionEntity, HttpServletRequest req) throws Exception {

        // 1.获取登录用户
        UserEntity loginUser = (UserEntity) req.getSession().getAttribute("loginUser");
        if (loginUser == null) {
            throw new JsonException(100,"登录超时,请先登录");
//            return R.error("登录超时，请先登录");
        }

        // 2.封装用户
        invitataionEntity.setUserId(loginUser.getId());
        invitataionEntity.setCreateTime(new Date());
        boolean add = invitationService.save(invitataionEntity);
        return R.out(add);
    }

    @GetMapping("/info/{id}")
    public String info(@PathVariable("id") Integer id, ModelMap map) throws Exception {
        // 1.查询帖子
        InvitataionEntity invitataionEntity = invitationService.getById(id);
        // 2.查询作者
        Integer userId = invitataionEntity.getUserId();
        UserEntity userEntity = userService.queryById(userId);

        // 3.查询帖子的评论
        List<CommentVo> commentEntityList = commentService.commentListByInvitataionId(invitataionEntity.getId());

        // 4.把帖子的数据和作者的数据放到map中
        map.put("topic", invitataionEntity);
        map.put("user", userEntity);
        map.put("commentVoList", commentEntityList);

        // 5.跳转到视图
        return "view/site/discuss-detail";
    }
}
